using B.S.XZYData.Api.Wrter.Application.Command.Process;
using B.S.XZYData.Domain.ZSHH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System.Transactions;
using Yitter.IdGenerator;
using System.Linq;

namespace B.S.XZYData.Api.Wrter.Application.Handler.Process
{
    /// <summary>
    /// 新增工序处理器
    /// </summary>
    public class AddProcessHandler : IRequestHandler<AddProcessCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Domain.ZSHH.Process> processRepo;
        private readonly IBaseRepository<ProcessCollectionData> collectionDataRepo;
        private readonly ILogger<AddProcessHandler> logger;

        public AddProcessHandler(
            IBaseRepository<Domain.ZSHH.Process> processRepo,
            IBaseRepository<ProcessCollectionData> collectionDataRepo,
            ILogger<AddProcessHandler> logger)
        {
            this.processRepo = processRepo;
            this.collectionDataRepo = collectionDataRepo;
            this.logger = logger;
        }

        /// <summary>
        /// 新增工序
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>返回统一包装类</returns>
        public async Task<ApiResult<int>> Handle(AddProcessCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<int>();

            try
            {
                // 验证工序名称唯一性
                var existingProcess = processRepo.GetAll()
                    .Where(x => !x.IsDeleted && x.ProcessName == request.ProcessName)
                    .ToList()
                    .FirstOrDefault();

                if (existingProcess != null)
                {
                    res.Msg = "工序名称已存在";
                    res.Code = ApiEnum.Fail;
                    return await System.Threading.Tasks.Task.FromResult(res);
                }

                using var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
                try
                {
                    // 生成雪花ID
                    var processId = YitIdHelper.NextId();
                    
                    // 自动生成工序编号（格式：年月日时分秒+6位随机数）
                    var processNumber = GenerateProcessNumber();

                    // 创建工序实体
                    var process = new Domain.ZSHH.Process
                    {
                        Id = processId,
                        ProcessNumber = processNumber,
                        ProcessName = request.ProcessName,
                        ReportingPermissions = request.ReportingPermissions,
                        ReportingRatio = request.ReportingRatio,
                        DefectiveItemList = request.DefectiveItemList,
                        TestField1 = request.TestField1,
                        TestField2 = request.TestField2,
                        Creator = request.Creator,
                        Updator = request.Creator
                    };

                    // 新增工序
                    var processResult = await processRepo.CreateAsync(process);
                    if (processResult <= 0)
                    {
                        res.Msg = "新增工序失败";
                        res.Code = ApiEnum.Fail;
                        return await System.Threading.Tasks.Task.FromResult(res);
                    }

                    // 新增工序采集数据（如果存在）
                    var collectionDataResult = 0;
                    if (request.CollectionDataList != null && request.CollectionDataList.Any())
                    {
                        var collectionDataEntities = request.CollectionDataList.Select(dto => new ProcessCollectionData
                        {
                            Id = YitIdHelper.NextId(),
                            ProcessId = processId,
                            DataType = dto.DataType,
                            DataName = dto.DataName,
                            Creator = request.Creator,
                            Updator = request.Creator
                        }).ToList();

                        collectionDataResult = await collectionDataRepo.CreateBatchAsync(collectionDataEntities);
                    }

                    transaction.Complete();

                    res.Data = processResult + collectionDataResult;
                    res.Msg = "新增工序成功";
                    res.Code = ApiEnum.Success;

                    logger.LogInformation($"新增工序成功，工序ID：{processId}，工序名称：{request.ProcessName}");
                }
                catch (Exception ex)
                {
                    logger.LogError($"新增工序事务异常：{ex.Message}");
                    res.Msg = "新增工序事务异常：" + ex.Message;
                    res.Code = ApiEnum.Error;
                }

                return await System.Threading.Tasks.Task.FromResult(res);
            }
            catch (Exception ex)
            {
                logger.LogError($"新增工序异常：{ex.Message}");
                res.Msg = "新增工序异常：" + ex.Message;
                res.Code = ApiEnum.Error;
                return await System.Threading.Tasks.Task.FromResult(res);
            }
        }

        /// <summary>
        /// 生成工序编号
        /// </summary>
        /// <returns>工序编号</returns>
        private string GenerateProcessNumber()
        {
            var timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
            var random = new Random();
            var randomPart = random.Next(100000, 999999).ToString();
            return timestamp + randomPart;
        }
    }
} 